<?php
class Content extends Atom {

  public static function get_id_by_path( $path ) {
    return db::q( "SELECT `id` FROM `content` WHERE `fullpath`='::1'", $path )->get('id');
  }
  
  public function load( $key ) {
    $sql = is_numeric($key) ? "SELECT * FROM `content` WHERE `id`=':i1' " : "SELECT * FROM `content` WHERE `alias`='::1' ";
    $args = func_get_args();
    for ( $i=1 ; array_key_exists($i, $args) ; $i++ ) {
      $sql .= ' AND '.$args[$i];
    }
    return $this->load_query( $sql, $key );
  }

  public function load_page( $key ) {
    if ( is_numeric($key) ) {
      return $this->load($key);
    }
    $sql = "SELECT * FROM `content` WHERE `type`!='' AND ( `fullpath`='::1' ";
    $path = $key;
    while (  $slash = strrpos( $path, '/' ) ) {
      $path = substr( $key, 0, $slash );
      $sql .= " OR `fullpath`='".$path."'";
    }
    $sql .= ' ) ';
    $args = func_get_args();
    for ( $i=2 ; array_key_exists($i, $args) ; $i++ ) {
      $sql .= ' AND '.$args[$i];
    }
    $sql .= " ORDER BY LENGTH(`fullpath`) DESC";
    return $this->load_query( $sql, $key );
  }


  
  
  public function create() {
    $filled = true;
    $fields = array('title','type');
    foreach ( $fields as $f ) {
      $filled = $fields && !empty( $this->data[$f] );
    }
    if ( $filled && !$this->id ) {
      empty( $this->data['alias'] )      && $this->data['alias']    = translit( $this->data['title'] );
      $this->data['fullpath'] = $this->data['alias'];
      if ( $this->data['parent'] ) {
        $parent = new Content();
        $parent->load( $this->data['parent'] );
        $this->data['fullpath'] = $parent->fullpath . '/' . $this->data['fullpath'];
      }
      $fields = array();
      $values = array();
      $res = db::q("DESCRIBE `content`");
      while ( $res->exists() ) {
        //$fields[ $res->Field ] = $res->assoc();
        if ( !empty( $this->{$res->Field} ) ) {
          $fields[] = ' `'.$res->Field.'` ';
          $values[] = " '".addslashes($this->{$res->Field})."' ";
        }
      }
      $sql = "INSERT INTO `content` (".implode(',',$fields).") VALUES (".implode(',',$values).")";
      if ( $success = db::q( $sql )->success() ) {
        $this->id = db::inserted();
      }
      return $success;
    }
    return false;
  }
  
  public function save() {
    $sql = "SELECT * FROM `content` WHERE `id`=':i1'";
    $old = db::q( $sql, $this->data['id'] ) -> assoc();
    $update = array();
    foreach ( $old as $field => $value ) {
      if ( isset($this->data[$field]) && $this->data[$field]!=$value ) {
        $update[] = " `$field`= '".addslashes($this->data[$field])."' ";
      }
    }
    $sql = "UPDATE `content` SET ".implode( ',', $update )." WHERE `id`=':i1'";
    db::q( $sql, $this->data['id'] );
  }


  public function load_query( $sql, $key ) {
    $res = db::q( $sql, $key );
    if ( $res->exists() ) {
      $this->data = $res->assoc();
      $this->template = $this->data['template'];
      return true;
    }
    return false;
  }



  public function process( $stack=null ) {
    if ( mod::exists( $this->type ) ) {
      $mod = new Module( $this->type );
      $mod->caller = $this;
      return $mod->exec();
    } else {
      is_null($stack) && $stack=array();
      array_push( $stack, $this->id );
      $code = &$this->data['data'];
      preg_match_all("/\[\[([A-Za-z0-9]+):([A-Za-z0-9\.\/\_]+)\]\]/", $code, $matches, PREG_SET_ORDER);
      foreach ( $matches as $m ) {
        switch ( $m[1] ) {
          case 'mod':
            $mod = new Module($m[2]);
            $mod->caller = $this;
            $text = $mod->exec();
            break;
          case 'content':
            $c = new Content();
            $c->load_page($m[2]);
            if ( in_array( $c->id, $stack ) ) {
              $text = '<h2><b>Warning!</b> Content output cycle prevented.</h2>';
            } else {
              $text = $c->process( $stack );
            }
            break;
          default:
            $text = '';
            break;
        }
        $code = replace_once( $m[0], $text, $code );
      }
      return $this->data['data'];
    }
  }

  public function get_html( $var_name='elem' ) {
    if ( !empty($this->template) ) {
      $t = is_a($this->template, 'Template') ? $this->template : new Template($this->template);
      $t->assign( $var_name, $this );
      return $t;
    }
  }


  public function __toString() {
    $this->process();
    return $this->data['data'];
  }

}
?>